/**
 * 
 */
package com.an.framework.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;


/**
 * @author Administrator
 * 拦截器，类似于过滤器，对每一次请求起过滤作用
 * 
 * 继承HandlerInterceptorAdapter实现自定义拦截器
 */
@Component
public class ProcessTimeInterceptor extends HandlerInterceptorAdapter {

	private static final Logger log = (Logger) LoggerFactory.getLogger(ProcessTimeInterceptor.class);
	
	//在请求发生前执行
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		long startTime = System.currentTimeMillis();
		request.setAttribute("startTime", startTime);
		return true;
	}
	
	//在请求完成后执行
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		long startTime =  (Long) request.getAttribute("startTime");
		request.removeAttribute("startTime");
		long endTime = System.currentTimeMillis();
		log.info("本次请求处理的时间：" + (endTime - startTime) + "ms");
		request.setAttribute("handleTime", (endTime - startTime));
		
	}
}
